package com.erp.security;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import com.erp.Resource.Resouce;
import com.erp.entity.ErpLog;
import com.erp.entity.SystemLog;
import com.erp.service.SystemLogService;
/**
 * 对com.erp.control下的Control类中打有自定义注解（@ErpLog）的方法进行日志记录，
 * 具体用法参考SystemLogController类中对query方法的日志记录
 * 注：该功能模块在权限模块完成后需进一步完善
 * @author 李魏
 *
 */
@Aspect
public class SystemLogHand {
	@Autowired
    private SystemLogService systemLogService;
    
	public SystemLogService getSystemLogService() {
		return systemLogService;
	}

	public void setSystemLogService(SystemLogService systemLogService) {
		this.systemLogService = systemLogService;
	}
	
	@Pointcut("execution(* com.erp.control.*.*(..))")
	public  void abc(){
		
		
	}
	@Before("abc()")
	public void before(JoinPoint joinpoint)throws Exception{  
		String methodName = joinpoint.getSignature().getName();
		Object target = joinpoint.getTarget();
		Class[] parameterTypes = ((MethodSignature)joinpoint.getSignature()).getMethod().getParameterTypes();
		Method m =  target.getClass().getMethod(methodName, parameterTypes);
		if(m.isAnnotationPresent(ErpLog.class)){
			String sessionId = "" ;
			String enterIp = Resouce.getInstall().getUser().getRequestIp();
			sessionId =Resouce.getInstall().getUser().getSessionid(); 
			Resouce resouce = Resouce.getInstall();
			ErpLog erpLog = m.getAnnotation(ErpLog.class);
			SystemLog systemLog = new SystemLog();
			//设置日志信息
			String enter_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) ;
			String pk_user = resouce.getUser().getId()+"";
			String username = resouce.getUser().getUsername();
			String methodInfo = joinpoint.getSignature().toString() ;
			String description = erpLog.description();
			systemLog.setPk_user(pk_user);
			systemLog.setUser_name(username);
			systemLog.setEnter_method_time(enter_time);
			systemLog.setDescription(description);
			systemLog.setMethod_info(methodInfo);
			systemLog.setEnter_ip(enterIp);
			systemLog.setSession_id(sessionId);
			systemLogService.save(systemLog);
		}
	}

}
